#!/usr/bin/env bash
 
if [ $# -ne 2 ]
then
	echo "Please specify ebuild file and unpack, compile or all"
	exit 1
fi
 
if [ -e ebuild.conf ]
then
	source ebuild.conf
elif [ -e /etc/ebuild.conf ]
then
	source /etc/ebuild.conf
else
	echo "ebuild.conf not found. Exiting."
fi
 
if [ -z "$DISTDIR" ]
then
	if [ -d distfiles ]
	then
		DISTDIR=$(pwd)/distfiles
	else 	
		# set DISTDIR to /usr/src/distfiles if not already set
		DISTDIR=/usr/src/distfiles
	fi
fi
export DISTDIR
 
ebuild_unpack() {
	#make sure we're in the right directory
	cd ${ORIGDIR}
 
	if [ -d ${WORKDIR} ]
	then    
		rm -rf ${WORKDIR}
	fi
 
	mkdir ${WORKDIR}
	cd ${WORKDIR}
	if [ ! -e ${DISTDIR}/${A} ]
	then
		echo "${DISTDIR}/${A} does not exist.  Please download first."
		exit 1
	fi
	tar xzf ${DISTDIR}/${A}
	echo "Unpacked ${DISTDIR}/${A}."
	#source is now correctly unpacked
}
 
user_compile() {
	#we're already in ${SRCDIR}
	if [ -e configure ]
	then
		#run configure script if it exists
		./configure --prefix=/usr
	fi
	#run make
	make $MAKEOPTS MAKE="make $MAKEOPTS"  
} 
 
ebuild_compile() {
	if [ ! -d "${SRCDIR}" ]
	then
		echo "${SRCDIR} does not exist -- please unpack first."
		exit 1
	fi
	#make sure we're in the right directory
	cd ${SRCDIR}
	user_compile
}
 
export ORIGDIR=`pwd`
export WORKDIR=${ORIGDIR}/work
 
if [ -e "$1" ]
then
	source $1
else
	echo "Ebuild file $1 not found."
	exit 1
fi
 
export SRCDIR=${WORKDIR}/${P}
 
case "${2}" in
	unpack)
		ebuild_unpack
		;;
	compile)
		ebuild_compile
		;;
	all)
		ebuild_unpack
		ebuild_compile
		;;
	*)
		echo "Please specify unpack, compile or all as the second arg"
		exit 1
		;;
esac
